package com.zsinfo.guoss.supplier.fragment.PaySetting;


import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.example.netcenter.Event.Response;
import com.example.netcenter.NetCenter;
import com.example.netcenter.RetrofitBuilder;
import com.example.netcenter.Url.ConstantsCode;
import com.example.netcenter.bean.ErrorBean;
import com.google.gson.Gson;
import com.zsinfo.guoss.supplier.R;
import com.zsinfo.guoss.supplier.activity.PaySettingsActivity;
import com.zsinfo.guoss.supplier.utils.CommentUtil;
import com.zsinfo.guoss.supplier.utils.SharedPreferencesUtil;

import java.util.HashMap;
import java.util.Map;

import static com.zsinfo.guoss.supplier.utils.CommentUtil.showSingleToast;

/**
 * A simple {@link Fragment} subclass.
 */
public class Fragment_Validate extends Fragment {


    public Fragment_Validate() {

    }

    private PaySettingsActivity paySettingsActivity;
    private Button next_page;
    private Button btn_validate_request;
    private EditText validate_num;
    private TextView user_phone_num;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_fragment__validate, container, false);

        paySettingsActivity = (PaySettingsActivity) getActivity();

        next_page = (Button) view.findViewById(R.id.next_page);

        //每次进入Fragment 都给Button设置默认背景

        next_page.setEnabled(false);

        GradientDrawable drawable = (GradientDrawable) next_page.getBackground();

        drawable.setColor(getResources().getColor(R.color.wallet_gray_light));

        next_page.setTextColor(Color.BLACK);

        validate_num = (EditText) view.findViewById(R.id.validate_num);

        validate_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {


            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (validate_num.getText().length() >= 4) {
                    next_page.setEnabled(true);
                    GradientDrawable drawable = (GradientDrawable) next_page.getBackground();
                    drawable.setColor(getResources().getColor(R.color.main_color));
                    next_page.setTextColor(Color.WHITE);
                } else {
                    //导致全部按钮都变灰色
                    next_page.setEnabled(false);
                    GradientDrawable drawable = (GradientDrawable) next_page.getBackground();
                    drawable.setColor(getResources().getColor(R.color.wallet_gray_light));
                    next_page.setTextColor(Color.BLACK);
                }
            }
        });

        user_phone_num = (TextView) view.findViewById(R.id.user_phone_num);

        btn_validate_request = (Button) view.findViewById(R.id.btn_validate_request);

        String number = SharedPreferencesUtil.getFirmMobile();

        user_phone_num.setText(number.substring(0, 3) + "****" + number.substring(7, 11));

        next_page.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                walletVerifysms();

            }


        });


        btn_validate_request.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                getValidatedCode();

            }
        });


        return view;
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

    }


    @Override
    public void onResume() {
        super.onResume();
    }


    //验证 验证码
    private void walletVerifysms() {


        String phone = SharedPreferencesUtil.getFirmMobile();
        if (phone.isEmpty()) {
            showSingleToast("手机号码不能为空");
            return;
        }


        new NetCenter().GetNetCenter(RetrofitBuilder.CreateApi().SET_PASSWORD(ConstantsCode.set_password,
                SharedPreferencesUtil.getID(),
                validate_num.getText().toString(),
                "",
                "",
                ""), new Response() {
            @Override
            public void OK(Object data) {

                setGoTo();
            }

            @Override
            public void Fail(Throwable e) {
                if (!e.getLocalizedMessage().contains("100000") && e.getLocalizedMessage().contains("Code")) {
                    ErrorBean errorBean = new Gson().fromJson(e.getMessage(), ErrorBean.class);
                    showSingleToast(errorBean.getMsg());
                }
            }

            @Override
            public void complete() {


            }
        });

    }

    void setGoTo() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && getActivity().getCurrentFocus() != null) {
            if (getActivity().getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        paySettingsActivity.SMSCode = validate_num.getText().toString();
        paySettingsActivity.setFlag = 1;
        paySettingsActivity.switchFragment("Fragment_PwdSettings");
    }


    /**
     * 发送短信验证码:
     */
    private void getValidatedCode() {
        String mPhone = SharedPreferencesUtil.getFirmMobile();

        if (mPhone.isEmpty() || mPhone.length() < 11) {
            showSingleToast("号码无效");
            return;
        }

        new NetCenter().GetNetCenter(
                RetrofitBuilder.CreateApi().SENDSMS(ConstantsCode.gss_sms, mPhone), new Response() {
                    @Override
                    public void OK(Object data) {
                        btn_validate_request.setEnabled(false);

                        btn_validate_request.setClickable(false);

                        btn_validate_request.setBackgroundColor(getResources().getColor(R.color.gray));

                        CountDownTime.sendEmptyMessageDelayed(123, 1000);

                        showSingleToast("发送成功");
                    }

                    @Override
                    public void Fail(Throwable e) {
                        Log.e("lixl", e.getMessage());
                        if (e.getMessage().contains("Code")) {
                            ErrorBean errorBean = new Gson().fromJson(e.getMessage(), ErrorBean.class);
                            showSingleToast(errorBean.getMsg());
                        } else {
                            showSingleToast(e.getMessage());
                        }
                    }

                    @Override
                    public void complete() {

                    }
                });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    private int time = 60;
    Handler CountDownTime = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 123:
                    if (time > 0) {

                        time--;

                        btn_validate_request.setText(time + "s");

                        CountDownTime.sendEmptyMessageDelayed(123, 1000);

                    } else {
                        time = 60;
                        btn_validate_request.setEnabled(true);
                        btn_validate_request.setClickable(true);
                        btn_validate_request.setBackgroundColor(getActivity().getResources().getColor(R.color.main_color));
                        btn_validate_request.setText("获取验证码");
                    }
                    break;
            }
        }
    };
}
